package com.gitee.wsl.transform.encode.base

import com.gitee.wsl.ext.array.toBinaryString
import com.gitee.wsl.ext.base.BYTE_BITS
import com.gitee.wsl.ext.string.padding
import com.gitee.wsl.transform.encode.ByteArrayEncode
import com.gitee.wsl.transform.encode.ByteArrayEncodeDecode
import com.gitee.wsl.transform.encode.DecodeToByteArray


const val BASE16_DICT = "0123456789ABCDEF"
const val BASE16_BLOCK_SIZE = 4

internal object Base16: ByteArrayEncodeDecode<String> {
    override fun encode(src: ByteArray): String = src.encodeBase16()
    override fun decode(src: String): ByteArray = src.decodeBase16()


    /**
     * 将指定char值转换为Unicode字符串形式，常用于特殊字符（例如汉字）转Unicode形式<br></br>
     * 转换的字符串如果u后不足4位，则前面用0填充，例如：
     *
     * <pre>
     * '你' =》'\u4f60'
    </pre> *
     *
     * @param ch char值
     * @return Unicode表现形式
     */
    fun toUnicodeHex(ch: Char,lowerCase:Boolean = true,alphabets: String= (if (lowerCase) "0123456789abcdef" else "0123456789ABCDEF")): String {
        return "\\u" +  //
                alphabets[(ch.code shr 12) and 15] +  //
                alphabets[(ch.code shr 8) and 15] +  //
                alphabets[(ch.code shr 4) and 15] +  //
                alphabets[(ch).code and 15]
    }

}

val ByteArrayEncode.Companion.base16 : ByteArrayEncode<String> get() = Base16

val DecodeToByteArray.Companion.base16 : DecodeToByteArray<String> get() = Base16


 fun ByteArray.encodeBase16(dict: String = BASE16_DICT) =
    toBinaryString().chunked(BASE16_BLOCK_SIZE).joinToString("") {
        dict.ifEmpty { BASE16_DICT }[it.padding("0", BASE16_BLOCK_SIZE).toInt(2)].toString()
    }

 fun String.decodeBase16(dict: String = BASE16_DICT) =
    asIterable()
        .joinToString("") {
            dict
                .ifEmpty { BASE16_DICT }
                .indexOf(it)
                .toString(2)
                .padding("0", BASE16_BLOCK_SIZE, false)
        }
        .chunked(BYTE_BITS)
        .map { it.toInt(2).toByte() }
        .filter { it.toInt() != 0 }
        .toByteArray()

